<template>
    <fieldset>
        <legend>登入页</legend>
        用户名:
        <input type="text" v-model="username">
        <br>
        密码:
        <input type="password" v-model="password" @keydown.enter="submit">
        <br>
        <button @click="submit">点击登录</button>
        <loading v-if="flag">
            <template v-slot:content>
                <!-- <p>正在加载中...</p> -->
            </template>
        </loading>
    </fieldset>
</template>
<script setup>
// 引入loading组件
import loading from "./../loading/index.vue"
import { ref } from "vue"
import {storeToRefs} from "pinia"

//引入请求登入的方法
import { loginApi } from "@/api/users"

//引入users的store

import useUser from "@/store/users"

//引入组合式的路由api

import { useRouter } from "vue-router"

//路由对象
let router = useRouter()

//store对象
let userStore = useUser()
let {flag} = storeToRefs(userStore)
console.log(flag)


let username = ref("")

let password = ref("")
//登入方法
let submit = async () => {
    // console.log(username.value)
    // console.log(password.value)
    // 发送登入请求时,打开loading组件
    flag.value = true;
    //console.log(flag)
    try {
        let res = await loginApi(username.value, password.value)

        //成功登入
        if (res.data.state) {
            // 成功登入时关闭loading
            flag.value=false
            console.log(flag)
            
            // console.log(res)
            //将用户信息存储到pinia
            userStore.userInfo.value = res.data.userInfo;
            //将token存到本地
            sessionStorage.setItem('tk', res.data.token)
            //登入成功要跳转到首页
            router.push('/')

            
        } else {
            alert(res.msg)
        }

    } catch (e) {
        console.log(e.toString())
    }
}
</script>